<template>
  <div>
    <!--    面包屑导航区-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--    卡片内容列表区域-->
    <el-card class="box-card">
      <!--      搜索输入框-->
      <el-row >

        <el-col :span="10">
          <el-input @clear="getUserList" clearable placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select">
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="addUserDialogVisible = true" type="primary" >添加用户</el-button>
        </el-col>
      </el-row>

      <!--      用户列表区-->
      <el-table
        border
        stripe
        :data="userList"
        style="width: 100%">
        <el-table-column
          type="index"
          label="#"
        >
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          >
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          >
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>
        <el-table-column

          label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>

          </template>

        </el-table-column>
        <el-table-column width="180px" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              @click="handleEditDialogOpen(scope.row)"></el-button>
            <el-button
            size="mini"
            icon="el-icon-delete"
            type="danger"
            @click="handleDelete(scope.row.id)"></el-button>
            <el-tooltip :enterable = 'false'  class="item" effect="dark" content="分配角色" placement="top">
              <el-button
                size="mini"
                icon="el-icon-setting"
                type="success"
                @click="handleSet( scope.row)"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

      <!--分页功能-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!--添加用户弹框-->
    <el-dialog
      class="pub_dialog"
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%"
      @close="addUserDialogClosed"
      :lock-scroll="false"
      >

    <!--   内容主体区域   >-->
      <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="70px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item show-password label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
    <!--   内容底部区域   >-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="addUserDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
    </el-dialog>

    <!--修改用户弹框-->
    <el-dialog
      title="编辑用户"
      :visible.sync="editUserDialogVisible"
      width="50%"
      @close="roleUserDialogClosed"
    >

      <!--   内容主体区域   >-->
      <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="70px" >
        <el-form-item  label="用户名" prop="username">
          <el-input :disabled="true" v-model="editForm.username"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--   内容底部区域   >-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleUserDialogClosed = false">取 消</el-button>
        <el-button type="primary" @click="handleSetRole">确 定</el-button>
      </span>
    </el-dialog>

    <!--用户角色权限分配弹框-->
    <el-dialog
      title="分配角色"
      :visible.sync="rolesUserDialogVisible"
      width="50%"
      @close="rolesUserDialogClosed"
    >

      <p>当前用户：{{rolesUserInfo.username}}</p>
      <p>当前角色：{{rolesUserInfo.role_name}}</p>
      <p>
        分配新角色：
        <el-select v-model="seletRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </p>
      <!--   内容主体区域   >-->
      <!--   内容底部区域   >-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesUserDialogClosed">取 消</el-button>
        <el-button type="primary" @click="handleSetRole">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: '',
  data () {
    // 自定义验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      if (regEmail.test(value)) {
        return callback()
      }
      return callback(new Error('邮箱格式不对'))
    }

    // 自定义验证手机号
    var checkMobil = (rule, value, callback) => {
      const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (!reg.test(value)) {
        return callback(new Error('输入合法手机号'))
      }
      callback()
    }
    return {
      // 获取用户列表参数
      queryInfo: {
        query: '', // 查询条件
        pagenum: 1, // 页码
        pagesize: 2 // 每页多少条数据
      },
      // 用户列表数据
      userList: [],
      // 总数据
      total: 0,
      // 添加用户弹框是否打开
      addUserDialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单数据验证
      addFormrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobil, trigger: 'blur' }
        ]
      },
      // 编辑用户弹框是否打开
      editUserDialogVisible: false,
      // 编辑用户表单数据
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 编辑用户表单数据验证
      editFormrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobil, trigger: 'blur' }
        ]
      },
      // 删除用户弹框是否打开
      deleteUserDialogVisible: false,
      // 设置用户弹框是否打开
      setUserDialogVisible: false,
      // 用户角色分配弹框是否打开
      rolesUserDialogVisible: false,
      // 用户角色分配的用户
      rolesUserInfo: {},
      // 角色列表
      rolesList: [],
      // 已选择角色id
      seletRoleId: ''

    }
  },

  created () {
    this.getUserList()
  },

  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')

      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize改变
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getUserList()
      console.log(`每页 ${val} 条`)
    },

    // 监听当前页码改变
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      this.getUserList()
    },

    // 改变用户状态
    async userStateChange (userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('操作失败')
      }

      this.$message.success('状态改变成功')
    },

    // 监听添加用户关闭弹框事件重置表单
    addUserDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },

    // 确认添加用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('表单验证失败')
        // 发起添加用户网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('操作失败')
        }

        this.addUserDialogVisible = false
        this.$message.success('添加用户成功')
      })
    },

    // 编辑用户
    handleEditDialogOpen (user) {
      console.log(user)
      this.editUserDialogVisible = true
      this.editForm = user
    },
    // 监听编辑用户关闭弹框事件重置表单
    editUserDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑用户
    handleEdit () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('表单验证失败')
        // 发起编辑用户网络请求
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`, this.editForm)
        if (res.meta.status !== 200) {
          return this.$message.error('操作失败')
        }
        // 刷新数据列表
        this.getUserList()
        this.editUserDialogVisible = false
        this.$message.success('编辑用户成功')
      })
    },

    // 删除用户
    handleDelete (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发起编辑用户网络请求
        const { data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('操作失败')
        }
        // 刷新数据列表
        this.getUserList()
        this.editUserDialogVisible = false
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 设置用户角色弹框
    async handleSet (user) {
      // 在展示对话框前获取角色列表
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('操作失败')
      }
      this.rolesList = res.data
      this.rolesUserInfo = user
      this.rolesUserDialogVisible = true
    },

    // 设置用户角色
    async handleSetRole () {
      // 在展示对话框前获取角色列表
      const { data: res } = await this.$http.put(`users/${this.rolesUserInfo.id}/role`, { rid: this.seletRoleId })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('操作失败')
      }
      this.getUserList()
      this.rolesUserInfo = {}
      this.seletRoleId = ''
      this.rolesUserDialogVisible = false
    },

    // 监听分配角色关闭时间
    rolesUserDialogClosed () {
      this.seletRoleId = ''
      this.rolesUserInfo = {}
      this.rolesUserDialogVisible = false
    }

  }
}
</script>

<style scoped>

  .pub_dialog {
    display: flex;
    justify-content: center;
    align-items: Center;
    overflow: hidden;

  }
  .el-dialog {
    margin: 0 auto !important;
    height: 90%;
    overflow: hidden;

  }
  .el-dialog__body {
    position: absolute;
    left: 0;
    top: 54px;
    bottom: 0;
    right: 0;
    padding: 0;
    z-index: 1;
    overflow: hidden;
    overflow-y: auto;
  }
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 100%;
  }

</style>
